package cn.changeforyou.cmd.generator;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.apache.commons.collections.map.HashedMap;

/**
 * @author zhyu
 * @date 2021/2/19 11:11
 */
public class GeneratorContext {

    private Map<Class, Object> classMap = new HashMap<>();
    
    private Scanner sc = new Scanner(System.in);
    
    private Map<String, Object> keyMap = new HashedMap();
    
    public int useScannerCount;
    
    public void putInKeyMap(String key, Object data) {
        keyMap.put(key, data);
    }
    
    public <T> T getFromKeyMap(String key, Class<T> c) {
        if(keyMap.containsKey(key)) {
            return (T)keyMap.get(key);
        }
        return null;
    }
    
    public void putCmdParameters(CmdGenerator generator, CmdGeneratorParameter parameter) {
        classMap.put(generator.getClass(), parameter);
    }

    public CmdGeneratorParameter getCmdParameters(CmdGenerator generator) {
        return (CmdGeneratorParameter) classMap.get(generator.getClass());
    }
    
    public void putInClassMap(Object c) {
        classMap.put(c.getClass(), c);
    }
    
    public <T> T getFromClassMap(Class<T> c) {
        if (classMap.containsKey(c)) {
            return (T)classMap.get(c);
        }
        return null;
    }
    
    public Scanner getScanner(){
        useScannerCount++;
        return sc;
    }
    
    public void closeScanner(){
        useScannerCount--;
        if(useScannerCount <= 0) {
            sc.close();
        }
    }
}
